package com.itheima.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpServletRequest request){
//        log.info(username);
//        log.info(password);
    LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        String pwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        queryWrapper.eq(Employee::getPassword,pwd).eq(Employee::getUsername,employee.getUsername());

    Employee employee1 = employeeService.getOne(queryWrapper);
        System.out.println(employee1);


        if (employee1!=null){
        if (0==employee1.getStatus()){
            return R.error("员工已禁用！");
        }
        request.getSession().setAttribute("empId",employee1.getId());
        return R.success(employee1);

    }
//        Cookie cok=new Cookie("1","2");

    return R.error("登录失败！");


    }

    @PostMapping("/logout")
    public R loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功！");
    }
@PostMapping
    public R addEmployee(@RequestBody Employee employee){
    Long id = BaseContext.getId();
    employee.setCreateUser(id);
    employee.setUpdateUser(id);
    employee.setUpdateTime(LocalDateTime.now());
    employee.setCreateTime(LocalDateTime.now());
    String pwd = DigestUtils.md5DigestAsHex("123456".getBytes());
    employee.setPassword(pwd);

    employeeService.save(employee);
        return R.success("添加成功！");

    }

@GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        Page page1=new Page(page,pageSize);

        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);
        employeeService.page(page1,wrapper);


        return R.success(page1);
    }
    @PutMapping
    public R updateEmployee(@RequestBody Employee employee){

        employeeService.updateById(employee);
        return R.success("修改成功！");
    }
    @GetMapping("/{id}")
    public R updateById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);

        return R.success(employee);

    }
}
